<html>
<head>
    <meta charset="UTF-8">
    <title>js简单时分秒倒计时</title>
</head>
<style>
    .box {
background: #17deb9;
        width: 350px;
        height: 60px;
        text-align: center;
        border-radius: 30px;
    }
</style>

<body onload="countTime()">
<div class="box">
    <!--    <button onclick="countTime()">点击</button>-->
    <br>
    <span id="_d">00</span>
    <span id="_h">00</span>
    <span id="_m">00</span>
    <span id="_s">00</span>
</div>
</body>
<script type="text/javascript">
    function countTime() {
        //获取当前时间
        var date = new Date();
        var now = date.getTime();
        //设置截止时间
        var str = "2023/9/14 12:28:34";
        var endDate = new Date(str);
        var end = endDate.getTime();

        //时间差
        var leftTime = end - now;
        //定义变量 d,h,m,s保存倒计时的时间
        var d, h, m, s;
        if (leftTime >= 0) {
            d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
            h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
            m = Math.floor(leftTime / 1000 / 60 % 60);
            s = Math.floor(leftTime / 1000 % 60);
        } else {
            d = 0;
            h = 0;
            m = 0;
            s = 0
        }
        //将倒计时赋值到div中(普通的写法)--1
        // document.getElementById("_d").innerHTML = d+"天";
        // document.getElementById("_h").innerHTML = h+"时";
        // document.getElementById("_m").innerHTML = m+"分";
        // document.getElementById("_s").innerHTML = s+"秒";
        // -------------------------
        //将倒计时赋值到div中(小于0，补0)--2
        // 定义 小于0补0 的方法zero
        function zero(num) {
            if (num < 10) {
                return "0" + num
            }
            return num
        }

        var mmm = setInterval(function (){
            // 赋值到div中
            document.getElementById("_d").innerHTML = zero(d) + "天";
            document.getElementById("_h").innerHTML = zero(h) + "时";
            document.getElementById("_m").innerHTML = zero(m) + "分";
            document.getElementById("_s").innerHTML = zero(s) + "秒";
            // -------------------------------
            let box = document.querySelector('.box') //获取元素

            if (leftTime<=0) {
                box.style.background = 'red';
                // alert('事件到啦~秒杀！！！');
                console.log('0')
                clearInterval(mmm)

            }
        },1000)
        //递归每秒调用countTime方法，显示动态时间效果
        // setTimeout(countTime, 1000);
        // 倒计时 事件到了 弹出提醒


    }
</script>
</html>
